<?php

class GalleryController extends BackendController
{
	
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	// public function accessRules()
	// {
	// 	return array(
	// 		array('allow',  // allow all users to perform 'index' and 'view' actions
	// 			'actions'=>array('index','view'),
	// 			'users'=>array('*'),
	// 		),
	// 		array('allow', // allow authenticated user to perform 'create' and 'update' actions
	// 			'actions'=>array('create','update','upload','delete_item'),
	// 			'users'=>array('@'),
	// 		),
	// 		array('allow', // allow admin user to perform 'admin' and 'delete' actions
	// 			'actions'=>array('admin','delete','deleteallitem','delete_item'),
	// 			'users'=>array('admin'),
	// 		),
	// 		array('deny',  // deny all users
	// 			'users'=>array('*'),
	// 		),
	// 	);
	// }

	public function actionView($id)
	{
		$gallery_item = Item::model()->with('gallery')->findAllByAttributes(array('GalleryId' => $id));
		$this->render('view',array('items' => $gallery_item,'gallery' => $id));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		//Each a album have many items image.
			$model = new Gallery();
			
			if(isset($_POST['Gallery']))
			{
				//Create new album, gallery
				$model->attributes = $_POST['Gallery'];
				$model->CreateDate = date('Y-m-d H:i:s');
				$model->UpdateDate = date('Y-m-d H:i:s');
				$model->save();
				//return id of lastest records.
				$gallery_id = $model->GalleryId;
				// Get image item from client uploaded
				$image = CUploadedFile::getInstancesByName('items');

				if(isset($image) && count($image) >= 1){
					//Set default thumnails for first image
					$i = 0;
					foreach ($image as $key => $value) {
						$i++;
						$gallery_item = new Item();
						$gallery_item['GalleryId'] = $gallery_id;
						$gallery_item['File_ext'] = $value->type;
						$gallery_item['Old_name'] = $value->name;
						$ran = rand(0,999999999);
                        $fileName = trim(date('Y-m-d H-i-s') . $ran) . '.'.$value->extensionName;
						$gallery_item['ItemName'] = $fileName;
						$gallery_item['Url'] = Yii::app()->basePath . "/../images/products/";
						if ($i == 1) {
							$gallery_item['Thumb_nails'] = 1;
						}
						else{
							$gallery_item['Thumb_nails'] = 0;
						}
						
						$gallery_item->save();	
						$value->saveAs(Yii::app()->basePath . "/../images/products/$fileName");
					}			
				}
				$this->redirect(Yii::app()->createAbsoluteUrl('store/backend/gallery/index'));				
			}
			$this->render('create', array('model' => $model));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Gallery']))
		{
			$model->attributes=$_POST['Gallery'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->GalleryId));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	public function actionDelete_item()
		{
			$gallery_item = Item::model()->findByPk($_POST['id']);
			if (isset($gallery_item)) {
				$file_image = Yii::app()->basePath . "/../images/products/" . $gallery_item->ItemName;
				// var_dump($file_image);die();
				if (file_exists($file_image)) {
					unlink($file_image);
				}
				if($gallery_item->delete()) 
					echo CJSON::encode(1);
			}
		}

	public function actionDelete($id)
	{
		$gallery = Gallery::model()->findByPk($id);
			Product::model()->updateAll(array('GalleryId'=> null),'GalleryId>=:GalleryId',array(':GalleryId'=>$gallery->GalleryId));
			$this->actionDeleteAllItem($gallery->id);
			if ($gallery->delete()) 
				$this->redirect(Yii::app()->createAbsoluteUrl(Yii::app()->baseUrl . 'store/backend/product'));
	}

	public function actionDeleteAllItem($gallery_id){
			$gallery_item = Item::model()->findAllByAttributes(array('GalleryId' => $gallery_id));
			if (isset($gallery_item)) {
				//delete Image
				foreach ($gallery_item as $key => $value) {
					$file_image = Yii::app()->basePath . "/../images/products/" . $value->name;
					
					if (file_exists($file_image)) {
						unlink($file_image);
					}
				}
				Item::model()->deleteAll('`GalleryId` = :gallery_id',array(
					':gallery_id'=>$gallery_id,
					));
			}

		}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$gallery = Item::model()->with('gallery')->findAll();
			// // $data = $gallery->findAll();
			// var_dump($gallery);
			$this->render('index',array('gallery' => $gallery));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Gallery('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Gallery']))
			$model->attributes=$_GET['Gallery'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Gallery the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=Gallery::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param Gallery $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='gallery-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	public function actionUpload($id)
		{
			$gallery = Gallery::model()->with('items')->findByPk($id);
			if (isset($_POST['Gallery'])) {
				// var_dump($_POST['items']);die();
				$image = CUploadedFile::getInstancesByName('items');
				if(isset($image)){
					//Set default thumnails for first image
					$i = 0;
					foreach ($image as $key => $value) {
						
						$i++;
						$gallery_item = new Item();
						$gallery_item['GalleryId'] = $id;
						$gallery_item['File_ext'] = $value->type;
						$gallery_item['Old_name'] = $value->name;
						$ran = rand(0,999999999);
                        $fileName = trim(date('Y-m-d H-i-s') . $ran) . '.'.$value->extensionName;
						$gallery_item['ItemName'] = $fileName;
						$gallery_item['Url'] = Yii::app()->baseUrl . "/../images/products/";
						$gallery_item->save();	
						$value->saveAs(Yii::app()->basePath . "/../images/products/$fileName");
					}			
				}
				$this->redirect(Yii::app()->createAbsoluteUrl('store/backend/gallery/view',array('id' => $id)));
			}
			$this->render('upload',array('gallery' => $gallery));
		}
}
